package vashion.azeroth.back.core.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import vashion.azeroth.back.core.context.BackUserContext;
import vashion.azeroth.core.personal.pojo.PersonalMember;

/**
 * 后台登陆校验
 */
public class BackLoginFilter implements Filter {

    private final static Logger log = LoggerFactory.getLogger(BackLoginFilter.class);
    
    @Override
    public void init(FilterConfig arg0) throws ServletException {
    }

    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        if (req.getRequestURI().contains("/back/login/login.htm") || req.getRequestURI().contains("/back/login/index.htm") 
        		 || req.getRequestURI().contains("/back/login/logout.htm")) {
            chain.doFilter(req, res);
        } else {

            PersonalMember loginUser = (PersonalMember) req.getSession().getAttribute(BackUserContext.LOGIN_USER);
            if (null == loginUser) {
                //直接页面跳转到登录页面
            	String path = req.getContextPath();
            	String basePath = req.getScheme()+"://"+req.getServerName()+":"+req.getServerPort()+path;
            	HttpServletResponse resp = (HttpServletResponse) response;
            	resp.setHeader("Cache-Control", "no-store");  
            	resp.setDateHeader("Expires", 0);  
            	resp.setHeader("Prama", "no-cache");  
            	resp.sendRedirect(basePath+"/back/login/index.htm");
            } else {
                chain.doFilter(req, res);
            }
        }
    }
}
